#include "bullet.h"
#define BULLET_SPEED 0.4f

CBullet::CBullet() : CMovable()
{
	life = 0;
}

CBullet::~CBullet()
{
}

void CBullet::ActivateBullet(int way, float X, float Y)
{
	reality = 13;
	pos_x = X+10;
	pos_y = Y-20;
	movingWay = way;
	v_x = BULLET_SPEED;
	if(way == 0) v_x = - v_x;
	v_y = 0.4f;
	width = 8;
	height = 8;
	life = 1;
	lowest = Y;
	anim = 0;
	state = 0;
}

void CBullet::Explode(int t)
{
	life = 0;
	state = 2;
	width = 16;
	height = 16;
}

void CBullet::Update(int t)
{
	pos_x += v_x * t;
	pos_y += v_y * t;

	cTree->Check(pos_x+width-1,pos_y-height+5,1,height-10);
	if(cTree->lastRes > 0)
	{
		if(ArrayObj[cTree->res[0]]->reality < 10 || ArrayObj[cTree->res[0]]->reality >= 20)
		{
			if(ArrayObj[cTree->res[0]]->reality > 10)
				ArrayObj[cTree->res[0]]->Die();
			Explode(t);
		}
	}

	cTree->Check(pos_x+1,pos_y-height+5,1,height-10);
	if(cTree->lastRes > 0)
	{
		if(ArrayObj[cTree->res[0]]->reality < 10 || ArrayObj[cTree->res[0]]->reality >= 20)
		{
			if(ArrayObj[cTree->res[0]]->reality > 10)
				ArrayObj[cTree->res[0]]->Die();
			Explode(t);
		}
	}

	cTree->Check(pos_x+2,pos_y+2,width-4,1);
	if(cTree->lastRes == 0 && v_y < 0.5f)
		v_y += 0.08f;
	else if(cTree->lastRes > 0)
	{
		if(ArrayObj[cTree->res[0]]->reality < 3)
		{
			v_y = -BULLET_SPEED;
			pos_y = ArrayObj[cTree->res[0]]->pos_y - ArrayObj[cTree->res[0]]->height;
		}
		else
		{
			ArrayObj[cTree->res[0]]->Die();
			Explode(t);
		}
	}
	if(pos_x > scr_x + 256 || pos_x < scr_x) life = 0;
}

void CBullet::RenderFrame(LPDIRECT3DDEVICE9 d3ddv, int t)
{
	DWORD now = GetTickCount();
	Update(t);
	if (anim != 4 && now - last_time > 100)
	{
		anim=(anim+1) % 4;
		last_time = now;
	}
	SpriteHandlerBP->Begin(D3DXSPRITE_ALPHABLEND);
	if(state != 2)
	{
		if(movingWay == 1)
			BulletPic->Render(_BackBuffer,pos_x,pos_y,width,height,anim);
		else
			BulletPic->Render(_BackBuffer,pos_x,pos_y,width,height,5+anim);
	}
	else
		BulletPic->Render(_BackBuffer,pos_x,pos_y,width,height,4);
	SpriteHandlerBP->End();
}